package com.myday.system.controller;

import java.net.http.WebSocket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.alibaba.fastjson2.JSONObject;
import com.myday.system.domain.dto.MessageDTO;
import com.myday.system.domain.vo.MessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
@ServerEndpoint("/websocket/{userId}")
//此注解相当于设置访问URL
public class WebSocketServerController {

    private Session session;

    private static CopyOnWriteArraySet<WebSocketServerController> webSockets =new CopyOnWriteArraySet<>();
    private static Map<Long,Session> sessionPool = new HashMap<Long,Session>();

    @Autowired
    private StringRedisTemplate redisTemplate;

    @OnOpen
    public void onOpen(Session session, @PathParam(value="userId")Long userId) {
        this.session = session;
        webSockets.add(this);
        sessionPool.put(userId, session);
        System.out.println(userId+"【websocket消息】有新的连接，总数为:"+webSockets.size());
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        System.out.println("【websocket消息】连接断开，总数为:"+webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }

    // 此为广播消息
    public void sendAllMessage(String message) {
        for(WebSocketServerController webSocket : webSockets) {
            System.out.println("【websocket消息】广播消息:"+message);
            try {
                webSocket.session.getAsyncRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // 此为单点消息
    public void sendOneMessage(MessageDTO messageDTO) {
        redisTemplate.opsForList().leftPush("chat", JSONObject.toJSONString(messageDTO));
        Session session = sessionPool.get(messageDTO.getUserId());
        if (session != null) {
            try {
//                session.getAsyncRemote().sendText(messageDTO.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendOneUserMessage(MessageDTO messageDTO) {
        Session session = sessionPool.get(messageDTO.getUserId());
        if (session != null) {
            try {
                MessageVO messageVO = new MessageVO();
                messageVO.setType("system");
                messageVO.setContent(messageDTO.getMessage());
                session.getAsyncRemote().sendText(JSONObject.toJSONString(messageVO));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}